package com.example.androidshixi;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {
    private EditText loginUsernameEditText, loginPasswordEditText;
    private Button loginButton, registerFromLoginButton;
    private UserSessionManager sessionManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        loginUsernameEditText = findViewById(R.id.login_username_edittext);
        loginPasswordEditText = findViewById(R.id.login_password_edittext);
        loginButton = findViewById(R.id.login_button);
        registerFromLoginButton = findViewById(R.id.register_from_login_button);
        sessionManager = new UserSessionManager(this);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = loginUsernameEditText.getText().toString().trim();
                String password = loginPasswordEditText.getText().toString().trim();
                if (!TextUtils.isEmpty(username) &&!TextUtils.isEmpty(password)) {
                    DatabaseHelper databaseHelper = new DatabaseHelper(LoginActivity.this);
                    boolean isLoginSuccess = databaseHelper.validateUser(username, password);
                    if (isLoginSuccess) {
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        sessionManager.saveUserLogin(username);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(LoginActivity.this, "登录失败，请检查用户名和密码", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(LoginActivity.this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
                }
            }
        });

        registerFromLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }
}

